<template>
    <div class="editor-container">
      <div class="toolbar">
        <input type="file" ref="fileInput"  @change="handleImageUpload" accept="image/*" style="display: none">
        <el-button type="primary" v-if="!isDisabled" @click="insertImage">插入图片</el-button>
      </div>
      <div class="editor-content" id="editor-content"  :contenteditable="!isDisabled" ref="editor" @paste="handlePaste" @keydown="handleKeyDown"></div>
    </div>
  </template>
  
  <script lang="ts">
  import { defineComponent, ref } from 'vue';
  import { uploadFile } from '@/api/system/upload'
  export default defineComponent({
    name: 'ImageTextEditor',
    props: {
      previewHtml: {
        type: String,
        default: ''
      },
       isDisabled:{
        type: Boolean,
        default:false
      },
    },
    setup() {
      const editor = ref<HTMLElement | null>(null);
      const fileInput = ref<HTMLInputElement | null>(null);
  
      // 插入图片按钮点击事件
      const insertImage = () => {
        fileInput.value?.click();
      };
  
      // 处理图片上传
      const handleImageUpload = (e: Event) => {
        const input = e.target as HTMLInputElement;
        if (input.files && input.files[0]) {
          const file = input.files[0];
          const reader = new FileReader();
          reader.onload = async (event) => {
            let imageUrl = ""
            const formData = new FormData();
            formData.append('file',file);
            await uploadFile(formData).then((res) =>{
                if(res.code == "00000"){
                    imageUrl = res.data.url;
                }
                insertImageElement(imageUrl);
            });
           
          };
          
          reader.readAsDataURL(file);
        }
      };
  
      // 插入图片元素到编辑器
      const insertImageElement = (imageUrl: string) => {
        if (!editor.value) return;
        const selection = window.getSelection();
        if (!selection || selection.rangeCount === 0) return;
        
        const range = selection.getRangeAt(0);
        const editorContent = document.getElementById('editor-content')
        // const editorContent = document.getElementsByClassName('editor-content'); // 获取编辑器根元素
        range.deleteContents();
    
        const img = document.createElement('img');
        img.src = imageUrl;
        img.style.maxWidth = '30%';
        img.style.height = 'auto';
        
        // 关键点1：检查选区是否在编辑器根层级
        if (range.startContainer !== editorContent && !editorContent.contains(range.startContainer)) {
            // 如果不在编辑器内，追加到编辑器末尾
            editorContent.appendChild(img);
        } else {
            // 关键点2：找到最近的块级父元素
            let parent = range.startContainer;
            while (parent !== editorContent && parent.parentNode !== editorContent) {
                parent = parent.parentNode;
            }
            // 在编辑器直接子级插入
            if (parent.parentNode === editorContent) {
              range.setStartAfter(parent);
              range.collapse(true);
            }
            range.insertNode(img);
        }

        // 关键点3：移动光标到新元素后
        range.setStartAfter(img);
        range.collapse(true);
        selection.removeAllRanges();
        selection.addRange(range);
      };
  
      // 处理粘贴事件（支持直接粘贴图片）
      const handlePaste = (e: ClipboardEvent) => {
        if (!editor.value) return;
        const items = e.clipboardData?.items;
        if (!items) return;
        for (let i = 0; i < items.length; i++) {
          if (items[i].type.indexOf('image') !== -1) {
            e.preventDefault();
            const blob = items[i].getAsFile();
            if (blob) {
              const reader = new FileReader();
              reader.onload = (event) => {
                const imageUrl = event.target?.result as string;
                insertImageElement(imageUrl);
              };
              reader.readAsDataURL(blob);
            }
            return;
          }
        }
      };
  
      // 处理键盘事件（例如回车键行为）
      const handleKeyDown = (e: KeyboardEvent) => {
        if (e.key === 'Enter') {
          // 自定义回车键行为
          const selection = window.getSelection();
          if (!selection || !selection.rangeCount) return;
          
          const range = selection.getRangeAt(0);
          const node = range.startContainer;
          
          // 如果当前在图片描述中按回车，则在图片容器后插入新段落
          if (node.parentElement?.classList.contains('image-description')) {
            e.preventDefault();
            const imageContainer = node.parentElement?.parentElement;
            if (imageContainer) {
              const newParagraph = document.createElement('p');
              newParagraph.innerHTML = '<br>';
              imageContainer.after(newParagraph);
              
              // 移动光标到新段落
              const newRange = document.createRange();
              newRange.selectNodeContents(newParagraph);
              newRange.collapse(true);
              selection.removeAllRanges();
              selection.addRange(newRange);
            }
          }
        }
      };

    
      const setData = (valhtml: string) => {
        const editableElement = document.getElementById('editor-content') as HTMLElement;
        editableElement.innerHTML = valhtml; 
      };
  
      // 获取编辑器内容（可用于保存）
      const getContent = () => {
        return editor.value?.innerHTML || '';
      };
     
      
      return {
        editor,
        fileInput,
        insertImage,
        handleImageUpload,
        handlePaste,
        handleKeyDown,
        getContent,
        setData
      };
    }
  });
  </script>
  
  <style scoped>
  .editor-container {
    border: 1px solid #ddd;
    border-radius: 4px;
    padding: 10px;
    position: relative;
  }
  
  .toolbar {
    margin-bottom: 10px;
    position: absolute;
    right: 10px;
    bottom: 0;;
  }
  
  .editor-content {
    min-height: 200px;
    outline: none;
  }
  
  .image-container {
    display: inline-block;
    width: 30%;
    margin: 10px 0;
    border: 1px solid #eee;
    padding: 5px;
    border-radius: 4px;
  }
  
  .image-container img {
    display: block;
    margin-bottom: 5px;
  }
  
  .image-description {
    padding: 5px;
    color: #666;
    font-size: 0.9em;
    border-top: 1px dashed #eee;
  }
  
  .image-description:empty:before {
    content: attr(placeholder);
    color: #aaa;
  }
  
  .image-description:focus {
    outline: none;
    background-color: #f9f9f9;
  }
  </style>